package com.neusoft.hifly.push.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.alibaba.fastjson.support.springfox.SwaggerJsonSerializer;

import com.neusoft.hifly.core.token.config.JwtConfig;
import feign.codec.Encoder;
import springfox.documentation.spring.web.json.Json;

/**
 * Spring Cloud Feign 配置 FastJson
 */
@Configuration
public class FeignConfig {

	@Autowired(required = false)
	private JwtConfig jwtConfig;

	/**
	 * 加载Feign拦截器
	 *
	 * @return 拦截器
	 */
	@Bean
	public FeignClientIntercepter feighHttpHeader() {
		return new FeignClientIntercepter(jwtConfig);
	}

	/**
	 * 加载Feign编码
	 *
	 * @return 编码
	 */
	@Bean
	public Encoder feignEncoder() {
		return new SpringEncoder(feignHttpMessageConverter());
	}

	private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
		final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(getFastJsonConverter());
		return () -> httpMessageConverters;
	}

	private FastJsonHttpMessageConverter getFastJsonConverter() {
		final FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

		final List<MediaType> supportedMediaTypes = new ArrayList<>();
		final MediaType mediaTypeJson = MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE);
		supportedMediaTypes.add(mediaTypeJson);
		converter.setSupportedMediaTypes(supportedMediaTypes);
		final FastJsonConfig config = new FastJsonConfig();
		config.getSerializeConfig().put(Json.class, new SwaggerJsonSerializer());
		config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
		converter.setFastJsonConfig(config);

		return converter;
	}

}
